package top.blentle.ai.data;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.apache.activemq.command.ActiveMQBytesMessage;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import top.blentle.ai.data.api.dto.LampEvent;
import top.blentle.ai.data.util.JsonMsg;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Topic;
import java.nio.charset.Charset;

/**
 * @author renhuan
 * @desc
 */
@Service
public class AiService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Resource
    private Topic reportTopic;

    @Resource
    private Topic dispatchTopic;

    public JsonMsg triggerEvent(LampEvent event) throws JMSException {
        logger.info("事件触发了.....客户端开始控制设备了,,,,", event);
        JsonMsg json = new JsonMsg();
        //ActiveMQBytesMessage msg = new ActiveMQBytesMessage();
        byte[] data = null;
        switch (event.getEventType()) {
            case on:
                data = getOnData(event);
                //data = "0=1".getBytes(Charset.forName("GBK"));
                break;
            case off:
                //data = "0=0".getBytes(Charset.forName("GBK"));
                data = getOffData(event);
                break;
            case color:
                break;
            case optics:
                break;
            default:
                break;
        }
        jmsMessagingTemplate.convertAndSend(dispatchTopic, data);
        json.setStatus(1);
        return json;
    }

    private byte[] getOffData(LampEvent event) {
        ByteBuf msg = Unpooled.buffer();
        //写协议头，12 表示命令
        msg.writeByte((byte) 12);
        //写12个字节
        msg.writeBytes(hexString2Bytes(event.getDeviceId()), 0, 12);
        //电量
        msg.writeByte((byte) 50);
        //供电方式
        msg.writeByte((byte) 64);
        //通信方式
        msg.writeByte((byte) 0);
        //设备厂家
        msg.writeInt(0);
        //设备型号
        msg.writeInt(0);
        //todo:计算总长度
        short total = 53;
        //写可变部分：
        //总长度
        msg.writeShort(total);
        //参数个数 5个
        msg.writeByte(5);
        //编码列表 0:表示开、关灯
        msg.writeByte(0);
        msg.writeByte(1);
        msg.writeByte(2);
        msg.writeByte(3);
        msg.writeByte(4);
        //数据条数:1条
        msg.writeByte((byte) 1);
        //写第一条数据:
        msg.writeByte(0);
        msg.writeByte(18);
        msg.writeByte(05);
        msg.writeByte(06);
        msg.writeByte(21);
        msg.writeByte(53);
        msg.writeByte(14);
        StringBuilder sb = new StringBuilder();
        sb.append("0=0").append("\t");
        sb.append("1=88").append("\t");
        sb.append("2=235").append("\t");
        sb.append("3=255").append("\t");
        sb.append("4=255").append("\t");
        msg.writeBytes(sb.toString().getBytes(Charset.forName("GBK")));
        int len = msg.readableBytes();
        byte[] data = new byte[len];
        msg.readBytes(data);
        String show = bytes2HexStr(data);
        System.err.println("dispatch data :" + show);
        return data;
    }


    private static String bytes2HexStr(byte[] byteArr) {
        if (null == byteArr || byteArr.length < 1) return "";
        StringBuilder sb = new StringBuilder();
        for (byte t : byteArr) {
            if ((t & 0xF0) == 0) sb.append("0");
            sb.append(Integer.toHexString(t & 0xFF));  //t & 0xFF 操作是为去除Integer高位多余的符号位（java数据是用补码表示）
        }
        return sb.toString();
    }


    /**
     * 16进制字符串转换成二进制数组
     *
     * @param hexstr
     * @return
     */
    public static byte[] hexString2Bytes(String hexstr) {
        byte[] b = new byte[hexstr.length() / 2];
        int j = 0;
        for (int i = 0; i < b.length; i++) {
            char c0 = hexstr.charAt(j++);
            char c1 = hexstr.charAt(j++);
            b[i] = (byte) ((parse(c0) << 4) | parse(c1));
        }
        return b;
    }

    private static int parse(char c) {
        if (c >= 'a')
            return (c - 'a' + 10) & 0x0f;
        if (c >= 'A')
            return (c - 'A' + 10) & 0x0f;
        return (c - '0') & 0x0f;
    }

    private byte[] getOnData(LampEvent event) {
        ByteBuf msg = Unpooled.buffer();
        //写协议头，12 表示命令
        msg.writeByte((byte) 12);
        //写12个字节
        msg.writeBytes(hexString2Bytes(event.getDeviceId()), 0, 12);
        //电量
        msg.writeByte((byte) 50);
        //供电方式
        msg.writeByte((byte) 64);
        //通信方式
        msg.writeByte((byte) 0);
        //设备厂家
        msg.writeInt(0);
        //设备型号
        msg.writeInt(0);
        //todo:计算总长度
        short total = 53;
        //写可变部分：
        //总长度
        msg.writeShort(total);
        //参数个数 5个
        msg.writeByte(5);
        //编码列表 0:表示开、关灯
        msg.writeByte(0);
        msg.writeByte(1);
        msg.writeByte(2);
        msg.writeByte(3);
        msg.writeByte(4);
        //数据条数:1条
        msg.writeByte((byte) 1);
        //写第一条数据:
        msg.writeByte(0);
        msg.writeByte(18);
        msg.writeByte(05);
        msg.writeByte(06);
        msg.writeByte(21);
        msg.writeByte(53);
        msg.writeByte(14);
        StringBuilder sb = new StringBuilder();
        int r = 255;
        int g = 255;
        int b = 255;
        if (StringUtils.isNotEmpty(event.getValue())) {
            String[] s = event.getValue().substring(4).replaceAll("\\)", "").split(",");
            r = Integer.parseInt(s[0].trim());
            g = Integer.parseInt(s[1].trim());
            b = Integer.parseInt(s[2].trim());
        }
        sb.append("0=1").append("\t");
        sb.append("1=88").append("\t");
        sb.append("2=" + r).append("\t");
        sb.append("3=" + g).append("\t");
        sb.append("4=" + b).append("\t");
        msg.writeBytes(sb.toString().getBytes(Charset.forName("GBK")));
        int len = msg.readableBytes();
        byte[] data = new byte[len];
        msg.readBytes(data);
        String show = bytes2HexStr(data);
        System.err.println("dispatch data :" + show);
        return data;
    }
}
